/**
 * 考勤管理-出差记录
 */
import React, { useEffect, useMemo } from 'react';
import { connect } from 'umi';
import moment from 'moment';
import { Form, Input, Button, Table, Card } from 'antd';
import { QuickForm, utils } from 'vv-frontend-components';
import { Link, router } from 'umi';
import Locale from '@/utils/locale';
import DateRange from '@/components/DateRange';
import { CompanyDepartPlus } from '@/containers';
import { dateConversion, download } from '@/utils/utils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import LinkTo from '@/components/LinkTo';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import { withRoutePage } from '@/utils/enhanceUtils';
import { Pagination } from '@/components';
import styles from './index.less';

const { locale } = new Locale('stat.overtime');
const { deepTrim } = utils;

const getSortStatus = (targetKey, bsOrder) => {
    if (!bsOrder) return '';
    const [key, order] = bsOrder.split(' ');
    const orderMap = {
        asc: 'ascend',
        desc: 'descend'
    };
    return key === targetKey ? orderMap[order] : '';
};

const List = ({ activeKey, form, overbusinessrecords, loading, dispatch, route, location }) => {
    const { getFieldsValue } = form;
    const { query } = location;
    const { companyCode: companyId, departmentCode: departmentId } = query;
    const { businessPagination: pagination, businessList: data, bsOrder } = overbusinessrecords;
    const { authCode } = new AuthCode(route.code);

    const getSearchData = pageNo => {
        const { companyDepart, date = { range: [] }, userName } = getFieldsValue();
        const payload = {
            companyCode: companyDepart?.companyId || '',
            departmentCode: companyDepart?.departmentId || '',
            startTime: date.range[0] ? date.range[0].format('YYYY-MM-DD') : '',
            endTime: date.range[1] ? date.range[1].format('YYYY-MM-DD') : '',
            employeeName: userName || '',
            pageNo: pageNo || query.pageNo,
            pageSize: query.pageSize,
            dateType: date.type,
            orderByField: bsOrder
        };
        return payload;
    };
    const fetchList = (ctx = {}) => {
        const { pageNo = null } = ctx;
        dispatch(
            deepTrim({
                type: 'overbusinessrecords/fetchBusinessList',
                payload: getSearchData(pageNo)
            })
        );
    };

    const handleExport = () => {
        const { pageNo, pageSize, ...other } = getSearchData();
        download({
            getData: () =>
                dispatch({
                    type: 'overbusinessrecords/fetchBusinessExport',
                    payload: deepTrim(other)
                })
        });
    };
    const initCompanyDepart = companyId || departmentId ? { companyId, departmentId } : undefined;
    const config = [
        {
            field: 'companyDepart',
            label: '机构',
            config: {
                initialValue: initCompanyDepart
            },
            component: <CompanyDepartPlus />
        },
        {
            field: 'userName',
            label: '员工',
            config: {
                initialValue: query.employeeName || ''
            },
            component: <Input placeholder="输入姓名" />
        },
        {
            field: 'date',
            config: {
                initialValue: {
                    range: [
                        query.startTime ? moment(query.startTime) : moment().startOf('month'),
                        query.endTime ? moment(query.endTime) : moment()
                    ],
                    type: query.dateType || 'month'
                }
            },
            component: (
                <DateRange
                    range
                    type="month"
                    dateTypes={[
                        {
                            label: '本周',
                            type: 'week'
                        },
                        {
                            label: '本月',
                            type: 'month'
                        },
                        {
                            label: '本年',
                            type: 'year'
                        }
                    ]}
                />
            )
        },
        {
            component: (
                <div>
                    <Button type="primary" htmlType="submit">
                        {locale('form.search', false)}
                    </Button>
                    <AuthComponent code={authCode('export')}>
                        <Button
                            style={{ marginLeft: '5px' }}
                            onClick={handleExport}
                            disabled={loading.effects['overbusinessrecords/fetchBusinessList']}
                        >
                            导出
                        </Button>
                    </AuthComponent>
                </div>
            )
        }
    ];

    const columns = useMemo(
        () => [
            {
                title: '工号',
                dataIndex: 'userNo',
                key: 'userNo'
            },
            {
                title: '姓名',
                dataIndex: 'userName',
                key: 'userName'
            },
            {
                title: '组织机构',
                dataIndex: 'departName',
                key: 'departName'
            },
            {
                title: '开始时间',
                dataIndex: 'startTime',
                key: 'startTime',
                sortOrder: getSortStatus('start_time', bsOrder),
                sorter: true,
                render(text, record) {
                    if (record.startTime === '') {
                        return <span>--</span>;
                    }
                    return <span>{record.startTime}</span>;
                }
            },
            {
                title: '结束时间',
                dataIndex: 'endTime',
                key: 'endTime',
                render(text, record) {
                    if (record.endTime === '') {
                        return <span>--</span>;
                    }
                    return <span>{record.endTime}</span>;
                }
            },
            {
                title: '时长',
                dataIndex: 'tripLong',
                key: 'tripLong',
                sortOrder: getSortStatus('trip_long', bsOrder),
                sorter: true,
                render(text) {
                    return <span>{text === '' ? '--' : dateConversion(text, 8)}</span>;
                }
            },
            {
                title: '事由',
                dataIndex: 'tripReason',
                key: 'tripReason',
                width: 100,
                render: text => (
                    <p
                        style={{
                            width: '100px',
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            marginBottom: '0'
                        }}
                        title={text}
                    >
                        {text === '' ? '--' : text}
                    </p>
                )
            },
            {
                title: '相关流程',
                dataIndex: 'applicationNo',
                key: 'applicationNo',
                render(text, record) {
                    const { applicationNo } = record;
                    const isOldFlow = !applicationNo.includes('-');
                    const url = isOldFlow
                        ? '/office/institutions/flowManage/fullApprovalProcess/processDetail'
                        : '/personal/portal/myAuditRead/myAuditReadDetail';
                    const params = isOldFlow ? { applicationNo, linkFrom: '1' } : { applicationNo };

                    return (
                        <span>
                            {record.applicationNo ? (
                                <LinkTo to={url} query={params}>
                                    {record.applicationNo}
                                </LinkTo>
                            ) : (
                                '--'
                            )}
                        </span>
                    );
                }
            },
            {
                title: '操作',
                dataIndex: 'action',
                key: 'action',
                fixed: 'right',
                width: 100,
                render(text, record) {
                    return record.status === 0 ? (
                        '--'
                    ) : (
                        <Link
                            to={{
                                pathname: '/office/personnelManagement/attendance/timetag/attendRecord/clockRecord',
                                query: {
                                    id: record.employeeCode,
                                    name: record.userName,
                                    startTime: record.startTime,
                                    endTime: record.endTime
                                }
                            }}
                        >
                            打卡记录
                        </Link>
                    );
                }
            }
        ],
        [bsOrder]
    );
    const tableChange = (newPagination, filters, sorters) => {
        let orderBy;
        let sorterField;
        const returnOrderBy = s => {
            if (s.field === 'startTime') {
                sorterField = 'start_time';
            }
            if (s.field === 'endTime') {
                sorterField = 'end_time';
            }
            if (s.field === 'tripLong') {
                sorterField = 'trip_long';
            }
            orderBy = `${sorterField} ${s.order.replace('end', '')}`;
        };
        if (sorters) {
            if (sorters && sorters.field && sorters.order) {
                returnOrderBy(sorters);
            } else if (typeof sorters === 'string') {
                orderBy = '';
            }
            dispatch({
                type: 'overbusinessrecords/save',
                payload: {
                    bsOrder: orderBy || ''
                }
            });
        }
        history.push({ query: { ...query, pageNo: 1 } });
    };

    const changePagination = _pagination => {
        history.push({ query: { ...query, pageNo: _pagination.current, pageSize: _pagination.pageSize } });
    };

    // 每当分页数或页数改变时均应该重新请求表格数据
    useEffect(() => {
        fetchList();
    }, [activeKey, overbusinessrecords.bsOrder, query.pageNo, query.pageSize]);

    return (
        <PageHeaderWrapper>
            <Card className={styles.tablebusi}>
                <Form
                    layout="inline"
                    style={{ marginBottom: 15 }}
                    onSubmit={e => {
                        e.preventDefault();
                        history.push({ query: getSearchData(1) });
                        fetchList({ pageNo: 1 });
                    }}
                >
                    <QuickForm form={form} config={config} />
                </Form>
                <Table
                    bordered={false}
                    scroll={{ x: 'max-content' }}
                    columns={columns}
                    loading={loading.models.overbusinessrecords}
                    dataSource={data}
                    rowKey="id"
                    onChange={tableChange}
                    pagination={false}
                />
                <Pagination
                    onChange={changePagination}
                    current={query.pageNo}
                    pageSize={query.pageSize}
                    total={pagination.total}
                    loading={loading.models.overbusinessrecords}
                />
            </Card>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ overbusinessrecords, loading }) => ({
        overbusinessrecords,
        loading
    }))(Form.create()(List))
);
